package com.grass.finding.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.grass.finding.common.BaseResponse;
import com.grass.finding.common.ErrorCode;
import com.grass.finding.exception.BusinessException;
import com.grass.finding.model.domain.Lost;
import com.grass.finding.model.dto.LostDto;
import com.grass.finding.service.LostService;
import com.grass.finding.utils.ResultUtil;
import com.grass.finding.utils.WXUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
public class LostController {

    @Autowired
    LostService lostService;

    /**
     * 上传发布的寻人信息
     * @param lost 请求的参数
     * @param req 获取openId
     * @return Lost对象
     */

    @PostMapping("/publishInformation")
    BaseResponse<Lost> publishInformation(@RequestBody Lost lost, HttpServletRequest req){
        String openId = WXUtil.getOpenId(req);
        lost.setOpenId(openId);
        boolean save = lostService.save(lost);
        if(!save){
            log.error("保存的发布寻人信息失败");
            throw new RuntimeException("系统错误");
        }
        return ResultUtil.success(lost);
    }

    @GetMapping("/publish")
    BaseResponse<List<LostDto>> publish(){
        List<LostDto> lostList = lostService.getPublish();
        return ResultUtil.success(lostList);
    }


    @GetMapping("/getMyPublish")
    BaseResponse<List<LostDto>> getPublishByOpenId(HttpServletRequest request){
        String openId = WXUtil.getOpenId(request);

        List<LostDto> lostList = lostService.getPublishByOpenId(openId);
        return ResultUtil.success(lostList);
    }
    @GetMapping("/getPublishByLostId")
    BaseResponse<LostDto> getPublishByLostId(HttpServletRequest request, Integer lostId){
//        String openId = WXUtil.getOpenId(request);

        LostDto lost = lostService.getPublishByLostId(lostId);
        return ResultUtil.success(lost);
    }
    @GetMapping("/searchByName")
    BaseResponse<List<LostDto>> searchByName(String searchField){
        if(StringUtils.isBlank(searchField)){
            throw new BusinessException(ErrorCode.INVALID_PARAMETER, "请求参数不能为空");
        }
        List<LostDto> list = lostService.searchByName(searchField);

        return ResultUtil.success(list);
    }
    @DeleteMapping("/deletePublish")
    BaseResponse<Boolean> deletePublish(HttpServletRequest request, Integer lostId){
        boolean remove = lostService.deleteByLostId(lostId);
        if(!remove){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return ResultUtil.success(true);
    }


}
